import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Scanner;

import protocol.ConnectionDiscover;
import protocol.OnConnectionUpdatesListener;
import protocol.OnNewMessageListener;
import protocol.PairedConnection;
import protocol.User;


public class Test {

	private static ConnectionDiscover discover;
	private static PairedConnection pair;
	private static Collection <User> myUsers;

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		String local = "";
		try {
			local = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			System.out.println("No se pudo obtener la Ip local");
			System.exit(0);
		}

		discover = new ConnectionDiscover("mac", local, new OnConnectionUpdatesListener() {

			@Override
			public void onUsersListUpdated(Collection<User> users) {
				myUsers = users;
			}

			@Override
			public void onNewConnection(User user) {
			}

		}, new OnNewMessageListener() {

			@Override
			public int onNewMessage(String message) {
				System.out.println("-- Mensaje >>"+message);
				return message.length();
			}

			@Override
			public void getPairedConnection(PairedConnection connection) {
				pair = connection;
			}

			@Override
			public void onCloseConnection() {
				pair = null;
			}
		});


		final Scanner lector = new Scanner(System.in);
		new Thread(new Runnable() {

			@Override
			public void run() {

				while(true) {

					String toSend = lector.nextLine();
					if(pair != null) {
						if(toSend.equals("d"))
							pair.closeConnection();
						else
							pair.sendMessage(toSend);
					} else if(toSend.equals("u")) {
						for (User user : myUsers)
							System.out.println("- "+user.getName());
					} else {
						try{
							int indexToConnect = Integer.valueOf(toSend);
							if(discover.connectTo(indexToConnect)) {
								System.out.println("Conexion valida");
							} else {
								System.out.println("Conexion invalida");
							}
						} catch(Exception e) {

						}
					}

				}

			}
		}).start();

		System.out.println("Fin de la creacion del Test");

	}

}
